package com.blogs.ui;


import java.io.InputStream;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blogs.component.BaseActivity;
import com.blogs.entity.AppConfig;
import com.blogs.entity.AppEnums;
import com.blogs.service.AddFavorite;
import com.blogs.service.AddFavorite.IMsgCallBack;
import com.blogs.service.GetBlogDetail;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.FormatTime;
import com.blogs.tools.HtmlFormat;
import com.blogs.tools.IO;
import com.cnblogs.R;
import com.cnblogs.R.color;

public class ContentActivity extends BaseActivity implements OnClickListener{
	private DBSharedPreferences sp;
	
	private String Id;// 博客编号
	private String Title;// 标题
	private String Author;// 作者
	private String publicDate;// 发表时间
	private String ViewCount;// 浏览次数
	private String url;//url
	private String blogapp;
	private String CommentCount;// 评论次数
	private int type;
	
	private Toast toast;
	
	private RelativeLayout title_top_bg;
	private RelativeLayout content_root;
	private LinearLayout content_buttom_ll;
	private ProgressBar webview_pb;
	private Button title_include_back;
	private TextView title_include_title;
	private LinearLayout content_detail_pb_ll;
	private LinearLayout content_detail_error_ll;
	private Button content_reload;
	private TextView content_detail_title_tv;
	private TextView content_detail_title_down_tv;
	private ImageView content_line;
	private WebView webview;
	
	private Button content_buttom_comment_btn;
	private Button content_buttom_share_btn;
	private Button content_buttom_collect_btn;
	
	private ProgressDialog proDdialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content_deail);
		sp=new DBSharedPreferences(this);
		init();
	}
	private void init()
	{
		ViewGroup headview=(ViewGroup)findViewById(R.id.main_title_include);
		title_include_title=(TextView)headview.findViewById(R.id.title_include_title);
		title_include_back=(Button)headview.findViewById(R.id.title_include_back);
		title_include_title.setText("正文");
		title_include_back.setVisibility(View.VISIBLE);
		title_include_back.setOnClickListener(this);
		title_top_bg=(RelativeLayout)headview;
		Id = getIntent().getStringExtra("Id");
		Title = getIntent().getStringExtra("Title");
		Author = getIntent().getStringExtra("Author");
		publicDate = getIntent().getStringExtra("publicDate");
		ViewCount = getIntent().getStringExtra("ViewCount");
		CommentCount = getIntent().getStringExtra("CommentCount");
		url=getIntent().getStringExtra("url");
		blogapp=getIntent().getStringExtra("blogapp");
		type=getIntent().getIntExtra("type", 0);
		
		content_detail_pb_ll=(LinearLayout)findViewById(R.id.content_detail_pb_ll);
		content_detail_error_ll=(LinearLayout)findViewById(R.id.content_detail_error_ll);
		content_reload=(Button)findViewById(R.id.content_reload);
		content_detail_title_tv=(TextView)findViewById(R.id.content_detail_title_tv);
		content_detail_title_down_tv=(TextView)findViewById(R.id.content_detail_title_down_tv);
		content_buttom_comment_btn=(Button)findViewById(R.id.content_buttom_comment_btn);
		content_buttom_collect_btn=(Button)findViewById(R.id.content_buttom_collect_btn);
		content_buttom_share_btn=(Button)findViewById(R.id.content_buttom_share_btn);
		content_buttom_ll=(LinearLayout)findViewById(R.id.content_buttom_ll);
		content_root=(RelativeLayout)findViewById(R.id.content_root);
		content_line=(ImageView)findViewById(R.id.content_line);
		webview_pb=(ProgressBar)findViewById(R.id.webview_pb);
		content_buttom_comment_btn.setOnClickListener(this);
		content_buttom_collect_btn.setOnClickListener(this);
		content_buttom_share_btn.setOnClickListener(this);
		content_reload.setOnClickListener(this);
		webview=(WebView)findViewById(R.id.webview);
		InitSkin();

		if(type==AppEnums.EnumContentType.blog)
		{
			content_buttom_collect_btn.setVisibility(View.VISIBLE);
		}
		else
		{
			content_buttom_collect_btn.setVisibility(View.GONE);
		}
		content_detail_title_tv.setText(Title);
		content_detail_title_down_tv.setText(Author+"  发布于"+FormatTime.format(publicDate)+"  浏览:"+ViewCount+"  评论:"+CommentCount);
		
		webview.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式
		webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		WebSettings webSetting = webview.getSettings();
		webSetting.setJavaScriptEnabled(true);
		webSetting.setDefaultFontSize(10);
		webSetting.setCacheMode(WebSettings.LOAD_DEFAULT
				| WebSettings.LOAD_CACHE_ELSE_NETWORK);
		webview.addJavascriptInterface(new JavaScriptInterface(this), "cnblogs");
		webview.setWebViewClient(new WebViewClient(){
			public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
				webview.loadUrl(url);
				
				return true;   
			}
		});
		webview.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				// Activity和Webview根据加载程度决定进度条的进度大小
				// 当加载到100%的时候 进度条自动消失
				ContentActivity.this.setProgress(progress * 100);
				webview_pb.setProgress(progress);
				if(progress==100)
				{
					webview_pb.setVisibility(View.GONE);
				}
				Log.i("progress", progress+"");
			}
		});
		this.InitProDailog();
		this.ShowLoading();//显示加载数据
		this.requestData();//请求数据
	}
	private void InitProDailog()
	{
		proDdialog = new ProgressDialog(this);
		proDdialog.setIndeterminate(true);
		proDdialog.setCancelable(true);
		proDdialog.setMessage("正在收藏...");
	}
	private void InitSkin()
	{
		if(sp.GetIsDarkState())
		{
			title_top_bg.getBackground().setLevel(2);
			content_buttom_ll.getBackground().setLevel(2);
			content_root.getBackground().setLevel(2);
			content_line.setVisibility(View.GONE);
			content_detail_title_tv.setTextColor(getResources().getColor(color.title_text_night));
		}
		else
		{
			title_top_bg.getBackground().setLevel(1);
			content_buttom_ll.getBackground().setLevel(1);
			content_root.getBackground().setLevel(1);
			content_detail_title_tv.setTextColor(getResources().getColor(color.title_text_light));
		}
	}
	private void ShowLoading()
	{

		webview.setVisibility(View.GONE);
		content_detail_pb_ll.setVisibility(View.VISIBLE);
		content_detail_error_ll.setVisibility(View.GONE);
		
	}
	private void ShowError()
	{
		webview.setVisibility(View.GONE);
		content_detail_pb_ll.setVisibility(View.GONE);
		content_detail_error_ll.setVisibility(View.VISIBLE);
	}
	private void ShowData()
	{
		webview.setVisibility(View.VISIBLE);
		content_detail_pb_ll.setVisibility(View.GONE);
		content_detail_error_ll.setVisibility(View.GONE);
	}
	private void requestData()
	{
		final Context context =this;
		new GetBlogDetail(this,type,type==AppEnums.EnumContentType.search_blog_detail?url:Id, new GetBlogDetail.IMsgCallBack() {
			
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				String html = "";
				try {
					InputStream inStream = getAssets().open("content.html");
					byte[] temp = IO.readInputStream(inStream);
					html = new String(temp);
				} catch (Exception e) {
					Log.e("error", e.toString());
				}
				Log.i("con_text_size", sp.GetTextSize()+"");
				String curs="";
				if( sp.GetTextSize()==AppConfig.TEXT_SIZE_SMALL)
				{
					curs="font-small";
				}
				else if(sp.GetTextSize()==AppConfig.TEXT_SIZE_MIDDLE)
				{
					curs="font-mid";
				}
				else
				{
					curs="font-big";
				}
				String skin="";
				if(sp.GetIsDarkState())
				{
					skin="night";
					result=result.replace("background-color: #F5F5F5;", "background-color: #4e4e4e;")
							.replace("color: #000000;", "color: #8590A2;")
							.replace("color: #0000ff;", "color: #1799ff;")
							.replace("color: #008000;", "color: #00b200;")
							.replace("color: #800000;", "color: #ca0000;");
				}
				else
				{
					skin="light";
				}
				html=html.replace("{%content%}", result).replace("{%size%}",curs).replace("{%skin%}", skin);

				
				html=HtmlFormat.FormatContent(context, html);
				Log.v("html", html);
				webview_pb.setVisibility(View.VISIBLE);
				webview.loadDataWithBaseURL("file:///android_asset/", html, "text/html",
						"utf-8", null);
				ShowData();
			}
			
			public void onFailed() {
				// TODO Auto-generated method stub
				ShowError();
			}
		}).loadData();
	}
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v==title_include_back)
		{
 	       finish();
		}
		else if(v==content_buttom_share_btn)
		{
			Intent intent = new Intent(Intent.ACTION_SEND); //启动分享发送的属性
            intent.setType("text/plain");                                    //分享发送的数据类型
            intent.putExtra(Intent.EXTRA_SUBJECT, Title);    //分享的主题
            intent.putExtra(Intent.EXTRA_TEXT,"博客园"+ Title+url);    //分享的内容
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//这个也许是分享列表的背景吧
            ContentActivity.this.startActivity(Intent.createChooser(intent, "分享"));//目标应用选择对话框的标题
		}
		else if(v==content_buttom_collect_btn)
		{
			final String favo_url="http://www.cnblogs.com/"+blogapp+"/p/"+Id+".html";
			new AlertDialog.Builder(ContentActivity.this)  
			.setTitle("文章收藏") 
			.setMessage("是否收藏该文章？") 
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					proDdialog.show();
					new AddFavorite(sp.GetSessionID(), Title, favo_url, new IMsgCallBack() {
						
						public void onSuccess() {
							// TODO Auto-generated method stub
							showToast("收藏文章成功");
							sp.SetHasNewFavo(true);
							proDdialog.hide();
						}
						
						public void onFailed(String err) {
							// TODO Auto-generated method stub
							showToast("收藏文章失败,"+err);
							proDdialog.hide();
						}
					}).Add();
				}
			}) 
			.setNegativeButton("取消", null) 
			.show();
		}
		else if(v==content_buttom_comment_btn)
		{
			Intent intent=new Intent();
			intent.setClass(this,CommentActivity.class);
			intent.putExtra("comment_id", Id);
			intent.putExtra("Title", Title);
			intent.putExtra("type", type);
			intent.putExtra("blogapp", blogapp);
			startActivity(intent);
		}
		else if(v==content_reload)
		{
			this.ShowLoading();
			this.requestData();//请求数据
		}
	}
	public class JavaScriptInterface 
	{
		Context mContext;
		public JavaScriptInterface(Context context) {
			// TODO Auto-generated constructor stub
			mContext=context;
		}
		public void showImg(String url) 
		{   
			//跳转到图片浏览
			Intent intent=new Intent();
			intent.setClass(mContext, ImageShowActivity.class);
			intent.putExtra("imageurl", url);
			mContext.startActivity(intent);
//			Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();     
		}  
		public void openURL(String url)
		{
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			Uri content_url = Uri.parse(url);
			intent.setData(content_url);
			startActivity(intent);
		}
	}
	private void showToast(String text)
	{
		if (toast == null) {
			toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		} else {
			toast.setText(text);
			toast.setDuration(Toast.LENGTH_SHORT);
		}
		toast.show();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		proDdialog.dismiss();
	}
}
